// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command
const imagesCollection = db.collection('images')
const usersCollection = db.collection('users')

// 云函数入口函数
exports.main = async (event, context) => {
  const { page = 1, pageSize = 10 } = event
  const skip = (page - 1) * pageSize
  
  try {
    // 查询公开的图片，按创建时间倒序
    const imagesResult = await imagesCollection
      .where({
        isPublic: true
      })
      .orderBy('createdAt', 'desc')
      .skip(skip)
      .limit(pageSize)
      .get()
    
    // 获取总数，用于前端分页
    const countResult = await imagesCollection.where({
      isPublic: true
    }).count()
    
    // 如果没有图片，直接返回空数组
    if (!imagesResult.data || imagesResult.data.length === 0) {
      return {
        success: true,
        images: [],
        total: countResult.total,
        hasMore: false
      }
    }
    
    // 收集所有用户ID
    const userIds = [...new Set(imagesResult.data.map(img => img.userId))]
    
    // 批量查询用户信息
    const userMap = {}
    // 由于可能有多个用户，需要分批查询
    const batchSize = 20 // 小程序云开发限制单次查询不超过20个记录
    for (let i = 0; i < userIds.length; i += batchSize) {
      const batchIds = userIds.slice(i, i + batchSize)
      const users = await Promise.all(
        batchIds.map(id => usersCollection.doc(id).get())
      )
      
      users.forEach(user => {
        if (user && user.data) {
          userMap[user.data._id] = {
            nickName: user.data.nickName,
            avatarUrl: user.data.avatarUrl
          }
        }
      })
    }
    
    // 将用户信息关联到图片
    const images = imagesResult.data.map(img => {
      // 确保时间是可序列化的格式
      const createdAt = img.createdAt ? img.createdAt.getTime() : Date.now()
      
      return {
        id: img._id,
        prompt: img.prompt,
        imageUrl: img.imageUrl,
        createdAt,
        user: userMap[img.userId] || { nickName: '未知用户', avatarUrl: '' }
      }
    })
    
    return {
      success: true,
      images,
      total: countResult.total,
      hasMore: skip + images.length < countResult.total
    }
    
  } catch (err) {
    console.error('获取图片列表失败', err)
    return {
      success: false,
      message: '获取图片列表失败',
      error: err
    }
  }
} 